package com.ruoyi.project.blog.service.impl;


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.RedisConstants;
import com.ruoyi.common.utils.bean.IpUtil;
import com.ruoyi.common.utils.bean.ResponseResult;
import com.ruoyi.project.blog.domain.BTags;
import com.ruoyi.project.blog.domain.BWebConfig;
import com.ruoyi.project.blog.domain.vo.ApiArticleListVO;
import com.ruoyi.project.blog.domain.vo.SystemArticleListVO;
import com.ruoyi.project.blog.mapper.BArticleMapper;
import com.ruoyi.project.blog.mapper.BCategoryMapper;
import com.ruoyi.project.blog.mapper.BTagsMapper;
import com.ruoyi.project.blog.mapper.BWebConfigMapper;
import com.ruoyi.project.blog.service.IBHomeService;
import com.ruoyi.project.blog.service.IBRedisService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

import static com.ruoyi.common.constant.FieldConstants.LIMIT_ONE;

@Service
@RequiredArgsConstructor
public class BHomeServiceImpl implements IBHomeService {

    private final IBRedisService redisService;

    private final BWebConfigMapper webConfigMapper;

    private final BArticleMapper articleMapper;

    private final BTagsMapper tagsMapper;

    private final BCategoryMapper categoryMapper;

    private final static String ak = "f94be500c45148bc185be24a38c04ad3";

    private final static String sk = "27563ca627d5db0d57e831ca4de0f75f";

    /**
     * 添加访问量
     *
     * @param request
     * @return
     */
    public ResponseResult report(HttpServletRequest request) {
        // 获取ip
        String ipAddress = IpUtil.getIp(request);
        // 获取访问设备
        UserAgent userAgent = IpUtil.getUserAgent(request);
        Browser browser = userAgent.getBrowser();
        OperatingSystem operatingSystem = userAgent.getOperatingSystem();
        // 生成唯一用户标识
        String uuid = ipAddress + browser.getName() + operatingSystem.getName();
        String md5 = DigestUtils.md5DigestAsHex(uuid.getBytes());
        // 判断是否访问
        if (!redisService.sIsMember(RedisConstants.UNIQUE_VISITOR, md5)) {
            // 访问量+1
            redisService.incr(RedisConstants.BLOG_VIEWS_COUNT, 1);
            // 保存唯一标识
            redisService.sAdd(RedisConstants.UNIQUE_VISITOR, md5);
        }
        return ResponseResult.success();
    }

    /**
     * 获取首页数据
     *
     * @return
     */
    public ResponseResult selectPubicData(Long userId) {
        //获取首页轮播
        List<SystemArticleListVO> articles = articleMapper.selectListByBanner(userId);
        LambdaQueryWrapper<BTags> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BTags::getUserId, userId);
        //获取标签云
        List<BTags> tags = tagsMapper.selectList(queryWrapper);
        //最新文章
        List<ApiArticleListVO> apiArticleListVOS = articleMapper.selectUpToDateArticle();
        return ResponseResult.success().putExtra("articles", articles).putExtra("newArticleList", apiArticleListVOS).putExtra("tagCloud", tags);
    }

    /**
     * 获取网站相关信息
     *
     * @return
     */
    public ResponseResult getWebSiteInfo() {
        //网站信息
        BWebConfig webConfig = webConfigMapper.selectOne(new LambdaQueryWrapper<BWebConfig>()
                .select(BWebConfig::getAuthorAvatar, BWebConfig::getIsMusicPlayer, BWebConfig::getAuthorInfo, BWebConfig::getTouristAvatar, BWebConfig::getBulletin,
                        BWebConfig::getQqNumber, BWebConfig::getGitee, BWebConfig::getGithub, BWebConfig::getLogo, BWebConfig::getWechat,
                        BWebConfig::getAboutMe, BWebConfig::getEmail, BWebConfig::getShowList, BWebConfig::getLoginTypeList,
                        BWebConfig::getRecordNum, BWebConfig::getAuthor, BWebConfig::getAliPay, BWebConfig::getWeixinPay,
                        BWebConfig::getQqGroup, BWebConfig::getWebUrl, BWebConfig::getSummary, BWebConfig::getName, BWebConfig::getKeyword)
                .last(LIMIT_ONE));

        //获取访问量
        Object count = redisService.getCacheObject(RedisConstants.BLOG_VIEWS_COUNT);
        //获取访客量
        Long visitorAccess = redisService.getCacheSetKeyNumber(RedisConstants.UNIQUE_VISITOR);
        //热门文章
        List<ApiArticleListVO> hotArticles = articleMapper.selectHotArticleList();
        return ResponseResult.success(webConfig).putExtra("siteAccess", Optional.ofNullable(count).orElse(0))
                .putExtra("visitorAccess", visitorAccess).putExtra("hotArticles", hotArticles);
    }

    /**
     * 获取各大平台的热搜
     *
     * @param type 平台
     * @return
     */
    @Override
    public ResponseResult hot(String type) {
        String url = "https://www.coderutil.com/api/resou/v1/" + type;
        JSONObject jsonObject = sendHttpUrl(url);
        return ResponseResult.success(jsonObject);
    }


    /**
     * 获取每日推荐歌曲
     *
     * @return
     */
    @Override
    public ResponseResult getMusic() {
        String url = "https://www.coderutil.com/api/music/v1/recommend";
        JSONObject jsonObject = sendHttpUrl(url);
        return ResponseResult.success(jsonObject);
    }

    /**
     * 发送api接口请求
     *
     * @param url 接口地址
     * @return
     */
    private static JSONObject sendHttpUrl(String url) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("access-key", ak);
        paramMap.put("secret-key", sk);
        String result = HttpUtil.get(url, paramMap);
        return JSONUtil.parseObj(result);
    }
}
